import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/entities/User';
import { UserWallet } from 'src/entities/UserWallet';
import { Connection, FindConditions, Repository } from 'typeorm';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User) protected repository:Repository<User>,
        private connection:Connection
    ){}

    async user(where:FindConditions<User>[] | FindConditions<User> | string, fields?:(keyof User)[]) {
        let user = await this.repository.findOne({
            where : where,
            select : fields
        })

        return user
    }

    async update(userId:number, data:{[key in keyof User]? : User[key]}) {
        const res = await this.repository.update(userId, data)
        return res.affected
    }

    async newUser(data:{[key in keyof User]? : User[key]}) {
        const queryRunner = this.connection.createQueryRunner()
        await queryRunner.connect();
        await queryRunner.startTransaction()

        try {
            
            const { raw } = await queryRunner.manager.insert<User>(User, data)
            if(!raw || raw.affectedRows < 1) {
                queryRunner.rollbackTransaction()
                return null
            }

            const userId = raw.insertId

            {
                const { raw } = await queryRunner.manager.insert<UserWallet>(UserWallet, {userId : userId})
                if(!raw || raw.affectedRows < 1) {
                    queryRunner.rollbackTransaction()
                    return null
                }
            }

            await queryRunner.commitTransaction()

            return userId

        } catch (error) {
            await queryRunner.rollbackTransaction()
        } finally {
            await queryRunner.release()
        }
    }
}